package com.canieatit.gwt.server;

import java.io.UnsupportedEncodingException;
import java.util.Properties;
import java.util.logging.Logger;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.restlet.resource.ServerResource;

import com.canieatit.gwt.shared.Product;
import com.canieatit.gwt.shared.ProductResource;

public class ProductServerResource extends ServerResource implements ProductResource {
	private static final Logger log = Logger.getLogger(ProductServerResource.class
			.getName());
	
	@Override
	public Product retrieve() {
		String barcode = getQuery().getFirstValue("barcode");
		String format = getQuery().getFirstValue("format");
		
		Product product = null;

		if (barcode != null) {
			product = DataStore.getFromDataStore(barcode);
			
			if (product != null ) {	
				return product;
			}
			
		}

		if (format.toLowerCase().contains("ean")) {
			format = "ean";
		} else {
			format = "upc";
		}

		if (product == null) {
			log.severe("Datastore returned null");
			product = UPCDatabaseChecker.lookup(format, barcode);

			if (product != null) {
				if (DataStore.putToDataStore(product)) {
					notifyAdmin(product, "UPCDatabaseChecker");
				}
			} else {
				log.warning("UPCDatabase returned null");
				product = new Product(barcode, "Product not found", "noCountry", "nosize");
			}
		}
		return product;
	}

	@Override
	public void store(Product product) {
		
		log.warning(product.barCode);
		if (product != null ) {
			if (DataStore.putToDataStore(product) ) {
				log.warning("Product written to datastore");
				notifyAdmin(product, "Restlet PUT");
				
			} else {
				log.warning("Product not found in datastore");
			}
		}
	}

	private void notifyAdmin(Product product, String source) {
		Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress("sa@dfarooq.com", "dfarooq.com Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                             new InternetAddress("sa@dfarooq.com", "Saad Farooq"));
            msg.setSubject("A new Product has been added");
            msg.setText(product.toString());
            Transport.send(msg);

        } catch (AddressException e) {
            e.printStackTrace();
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
	}

	@Override
	public void remove(Product product) {
		DataStore.deleteFromDataStore(product);
		
	}
	
}
